#!/bin/bash

# prepend a prefix file to the start of many target files

# exit statuses
INVALID_ARGS=1

function prependFile() {
	targetFile=$1
	if [ -f $targetFile ]; then
		mv $targetFile $targetFile.tmp
		cat $prefixFile $targetFile.tmp > $targetFile;
		rm $targetFile.tmp
	else
		echo "Target file does not exist: $targetFile"
		exit $INVALID_ARGS
	fi
}

if [ $# = 0 ]; then
	echo "Must supply a prefix file"
	exit $INVALID_ARGS
fi

prefixFile=$1;

if  ! [ -f $prefixFile ]; then
	echo "Prefix file does not exist: $prefixFile"
	exit $INVALID_ARGS
fi

shift

if [ $# -gt 0 ]; then
	for fileName in $@; do
		prependFile $fileName
	done
else
	while read fileName; do
		prependFile $fileName
	done
fi

exit 0
